package org.xq.modules.seckill.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.xq.common.service.impl.BaseServiceImpl;
import org.xq.common.utils.QueryHelpPlus;
import org.xq.dozer.service.IGenerator;
import org.xq.modules.seckill.domain.XqStoreSeckill;
import org.xq.modules.seckill.dto.XqStoreSeckillDto;
import org.xq.modules.seckill.dto.XqStoreSeckillQueryCriteria;
import org.xq.modules.seckill.mapper.StoreSeckillMapper;
import org.xq.modules.seckill.service.StoreSeckillService;
import org.xq.modules.shop.service.SystemGroupDataService;
import org.xq.utils.BeanUtil;
import org.xq.utils.FileUtil;
import org.xq.utils.OrderUtil;
import com.github.pagehelper.PageInfo;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

// 默认不使用缓存
//import org.springframework.cache.annotation.CacheConfig;
//import org.springframework.cache.annotation.CacheEvict;
//import org.springframework.cache.annotation.Cacheable;

/**
* @author admin
* @date 2021-05-13
*/
@Slf4j
@Service
@AllArgsConstructor
//@CacheConfig(cacheNames = "xqStoreSeckill")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class StoreSeckillServiceImpl extends BaseServiceImpl<StoreSeckillMapper, XqStoreSeckill> implements StoreSeckillService {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    StoreSeckillMapper seckillMapper;

    @Autowired
    SystemGroupDataService systemGroupDataService;

    private final IGenerator generator;


    @Scheduled(cron = "0 */5 * * * ?")
    public void pushSeckillToRedis(){

//        YxSystemGroupDataQueryCriteria criteria = new YxSystemGroupDataQueryCriteria();
//        criteria.setGroupName(ShopConstants.YSHOP_SECKILL_TIME);
        //秒杀活动时间段
//        List<SystemGroupData> systemGroupData = systemGroupDataService.queryAll(criteria);
//        for (SystemGroupData item : systemGroupData) {
//            String value = item.getValue();
//        }
        //查询未开始的秒杀活动信息
        List<XqStoreSeckill> seckillList = seckillMapper.selectSeckillOfNotStart();
        List<XqStoreSeckillDto> storeSeckillDTOS = generator.convert(seckillList, XqStoreSeckillDto.class);
        //秒杀商品存储到redis
        for (XqStoreSeckillDto seckill : storeSeckillDTOS) {
            String statusStr = OrderUtil.checkActivityStatus(seckill.getStartTime(), seckill.getStopTime(), seckill.getStatus());
            seckill.setStatusStr(statusStr);
            redisTemplate.opsForHash().put("xqshopping-seckill:seckill-info", seckill.getId().toString(), seckill );
            log.info("已将秒杀活动载入到redis中！");
        }

        //redis载入秒杀商品的库存信息
        for(XqStoreSeckill seckill: seckillList){
            Integer inventory = seckill.getStock(); //获取库存数
            List<Integer> skuIds = new ArrayList<>(inventory);
            for(int i=0; i<inventory; i++){
                skuIds.add(seckill.getId());
            }
            redisTemplate.opsForList().leftPushAll("xqshopping-seckill:seckill-inventory:" + seckill.getId() + seckill.getProductId(), skuIds);
        }

    }

    @Override
    //@Cacheable
    public Map<String, Object> queryAll(XqStoreSeckillQueryCriteria criteria, Pageable pageable) {
        getPage(pageable);
        PageInfo<XqStoreSeckill> page = new PageInfo<>(queryAll(criteria));
        List<XqStoreSeckillDto> storeSeckillDTOS = generator.convert(page.getList(), XqStoreSeckillDto.class);
        for (XqStoreSeckillDto storeSeckillDTO : storeSeckillDTOS){
            String statusStr = OrderUtil.checkActivityStatus(storeSeckillDTO.getStartTime(),
                    storeSeckillDTO.getStopTime(), storeSeckillDTO.getStatus());
            storeSeckillDTO.setStatusStr(statusStr); //设置秒杀状态
        }
        Map<String,Object> map = new LinkedHashMap<>(2);
        map.put("content",storeSeckillDTOS);
        map.put("totalElements", page.getTotal());
        return map;
    }

    @Override
    public Map<String, Object> getTodaySeckills() {
        Map<String, Object> entries = redisTemplate.opsForHash().entries("xqshopping-seckill:seckill-info");
        return entries;
    }


    @Override
    //@Cacheable
    public List<XqStoreSeckill> queryAll(XqStoreSeckillQueryCriteria criteria){
        return baseMapper.selectList(QueryHelpPlus.getPredicate(XqStoreSeckill.class, criteria));
    }


    @Override
    public void download(List<XqStoreSeckillDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (XqStoreSeckillDto yxStoreSeckill : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("商品id", yxStoreSeckill.getProductId());
            map.put("推荐图", yxStoreSeckill.getImage());
            map.put("轮播图", yxStoreSeckill.getImages());
            map.put("活动标题", yxStoreSeckill.getTitle());
            map.put("简介", yxStoreSeckill.getInfo());
            map.put("价格", yxStoreSeckill.getPrice());
            map.put("成本", yxStoreSeckill.getCost());
            map.put("原价", yxStoreSeckill.getOtPrice());
            map.put("返多少积分", yxStoreSeckill.getGiveIntegral());
            map.put("排序", yxStoreSeckill.getSort());
            map.put("库存", yxStoreSeckill.getStock());
            map.put("销量", yxStoreSeckill.getSales());
            map.put("单位名", yxStoreSeckill.getUnitName());
            map.put("邮费", yxStoreSeckill.getPostage());
            map.put("内容", yxStoreSeckill.getDescription());
            map.put("开始时间", yxStoreSeckill.getStartTime());
            map.put("结束时间", yxStoreSeckill.getStopTime());
            map.put("添加时间", yxStoreSeckill.getAddTime());
            map.put("产品状态", yxStoreSeckill.getStatus());
            map.put("是否包邮", yxStoreSeckill.getIsPostage());
            map.put("热门推荐", yxStoreSeckill.getIsHot());
            map.put("删除 0未删除1已删除", yxStoreSeckill.getIsDel());
            map.put("最多秒杀几个", yxStoreSeckill.getNum());
            map.put("显示", yxStoreSeckill.getIsShow());
            map.put(" endTimeDate",  yxStoreSeckill.getEndTimeDate());
            map.put(" startTimeDate",  yxStoreSeckill.getStartTimeDate());
            map.put("时间段id", yxStoreSeckill.getTimeId());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}
